#include "Button.hpp"

namespace mi
{
    Button::Button(std::string text) :
        Widget(tButton, text)
    {
        hoverOver = false;
        pressed = false;
        callableObject = NULL;
        callback = NULL;
        txt.setFont(Widget::defaultFont);
        txt.setCharacterSize(Widget::defaultFontSize);
        txt.setString(text);
    }

    void Button::SetCallbackFunction(Callable* object)
    {
        callableObject = object;
    }

    bool Button::IsPressed ()
    {
        return pressed;
    }

    Widget* Button::MouseClick(sf::Mouse::Button button, sf::MouseState state, int x, int y)
    {
        if ( button == sf::Mouse::Left)
        {
            if (IsMouseInBody(Vec2i(x,y)))
            {
                if (state == sf::Down)
                {
                    pressed = true;
                    return this;
                }
                else if (pressed) // and, implicitly, state == UP
                {
                    if (callableObject != NULL)
                        callableObject->EventCallback(Event(this, Vec2i(x,y)));
                    pressed = false;
                    return this;
                }
            }
            pressed = false;
            hoverOver = false;
        }
        
        return NULL;
    }

    Widget* Button::MouseMoved(int x, int y, int dx, int dy)
    {
        if (IsMouseInBody(Vec2i(x,y)) )
        {
            hoverOver = true;
            return this;
        }
        else
        {
            hoverOver = false;
        }
        return NULL;
    }

    Widget* Button::MouseDragged(int x, int y, int dx, int dy)
    {
        return NULL;
    }

    void Button::Draw2D ()
    {
        if (pressed)
        {
            DrawActiveFace(position, position + size);
        }
        else if (hoverOver)
        {
            DrawHoverFace(position, position + size);
        }
        else
        {
            DrawBackground(position, position + size);
        }
        Vec2i textSize = GetTextSize(text);
        Vec2i textPos = position + (size - textSize) / 2;
        SetTextPos(txt, textPos);
        RenderText(txt);
    }

    bool Button::Update (double dTime)
    {
        return false;
    }

    // Private functions

    void Button::DrawButtonFace(Vec2i start, Vec2i end)
    {
        DrawQuad(start, end, NULL, Vec3d(0.9, 0.46, 0.0));
    }

    void Button::DrawHoverFace(Vec2i start, Vec2i end)
    {
        DrawQuad(start, end, NULL, Vec3d(0.2, 0.4, 1.0));
    }

    void Button::DrawActiveFace(Vec2i start, Vec2i end)
    {
        DrawQuad(start, end, NULL, Vec3d(0.7, 0.9, 0.7));
    }
}